//
//  LKOAuthViewController.swift
//  新浪微博
//
//  Created by 胡不归是大虾 on 16/9/25.
//  Copyright © 2016年 胡不归是大虾. All rights reserved.
//

import UIKit
import SVProgressHUD
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userInfoModels.plist")
class LKOAuthViewController: UIViewController {
    //MARK:UI设置
    //实例化一个webView,用来显示授权界面
    lazy var webView = UIWebView()
    //自定义进度条
    lazy var progressView = LKProgressView()
    func setProgerssView()
    {
        self.view.addSubview(progressView)
        progressView.frame.origin.y = 64
    }
    override func loadView() {
        view = webView
        webView.delegate = self
        //将webView设置为透明,解决底部出现黑色栏的bug
        webView.isOpaque = false
        loadOAuthView()
        setNavigationBar()
        setProgerssView()
    }
    //MARK:设置导航栏
    func setNavigationBar () {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName:"", action: #selector(closeBtnItemDidClick), target: self, title: "关闭")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "", action: #selector(autoFillBtnItemDidClick), target: self, title: "自动填充")
    }
    //实现导航栏按钮方法
    func closeBtnItemDidClick() {
        dismiss(animated: true, completion: nil)
    }
    func autoFillBtnItemDidClick() {
        let jsString = "document.getElementById('userId').value = '15026662146', document.getElementById('passwd').value = 'onceforever5235' "
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    //MARK:加载授权界面
    func loadOAuthView () {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = URL(string: urlString)
        let urlRequest = URLRequest(url: url!)
        webView.loadRequest(urlRequest)
    }


}
    //MARK:webView代理方法
extension LKOAuthViewController: UIWebViewDelegate {
    //实现协议方法
    func webViewDidStartLoad(_ webView: UIWebView) {
        progressView.showLoadingView()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        progressView.showFinishView()
}
    //每次加载新的界面就会调用这个方法,在这里截取token
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //获取url中的绝对string
        let urlString = request.url?.absoluteString ?? ""
        //定义标识
        let flag = "code="
        //如果字符串包含flag字段,就进行截取
        if urlString.contains(flag) {
            //获取请求中包含的参数
            let query = request.url?.query ?? ""
            //对参数进行截取
            let code = (query as NSString).substring(from: flag.characters.count)
            //获取到code后再获取用户数据
//            loadAccessTokem(code: code)
            LKUserInforViewModel.sharedUserInfoViewModel.loadAccessTokem(code: code, finishedClosure: { (success) in
                if !success{
                    SVProgressHUD.showError(withStatus: "What the fuck!")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "Congratulations!")
                NotificationCenter.default.post(name: Notification.Name(KChangeRootVCNot), object: "welcome")
            })
            return false
        }
        return true
    }
}
